import { t } from 'i18next'
import React, { forwardRef, ReactNode, useEffect, useImperativeHandle } from 'react'
import { StyledVmpPoll } from './style'
import { Select, InputNumber, CheckBox, Message } from '@kedacom/react-next'
import { UserEntity } from '@/api/create/interface'
import { fetchGetPollPlanDetail, fetchGetPollPlanList, PollEntity } from '@/api/create/vmp'
import { useRequest } from 'ahooks'
import { useCreateContentStore } from '../../../store'
import LabelWrap from '../../../components/LabelWrap'
import CreateMember from '../../../components/CreateMember'
import { useBasicInfoStore } from '../../basicInfo/store'
import { Alert } from '@/components/Alert'
import shallow from 'zustand/shallow'
import { setTvwallPollList } from '../../../store.combine'
import { initPollData } from '../store.combine'
import { useMeetingTVWallStore } from '../store'
export class Poll {
	id: string
	mode: number
	name: string
	keep_time: number
	num: number
	members: UserEntity[]
	cur_poll_mt?: UserEntity
	poll_index?: number
	state?: 0 | 1 | 2
	constructor(poll: PollEntity) {
		this.id = poll.id ?? ''
		this.mode = poll.mode ?? 1
		this.name = poll.name ?? ''
		this.poll_index = poll.poll_index
		this.state = poll.state
		this.keep_time = poll.keep_time ?? 30
		this.num = poll.num ?? 0
		this.cur_poll_mt = undefined
		this.members = []
	}
}
export interface VmpPollProps {
	// pollData: Vmp['poll'] | null
	children?: ReactNode
}
/**轮询的数据 */
export interface PollRef {
	testValue: () => boolean
	getValue: () => Poll
}
const pollIntervalOptions = [
	{ label: t('15(快)'), value: 15 },
	{ label: t('30(中)'), value: 30 },
	{ label: t('60(慢)'), value: 60 },
	{ label: t('自定义'), value: 0 },
]
const TvwallPoll = forwardRef((props: VmpPollProps, ref: React.Ref<PollRef>) => {
	const { preKey, isTemplate, _container } = useCreateContentStore(
		(state) => ({ preKey: state.preKey, isTemplate: state.isTemplate, _container: state._container }),
		shallow
	)
	const repeat = useBasicInfoStore((state) => state.repeat)
	/**第一步:请求轮询预案数据*/
	const { data: planList } = useRequest(() => fetchGetPollPlanList(preKey, isTemplate))
	const {
		update,
		setBatchPollParams,
		pollPlanOptions,
		pollPlanValue,
		pollIntervalOptionsVal,
		pollInterval,
		pollTimes,
		unlimited,
		pollPlanName,
		pollMembers,
		correct_style,
		show_mt_name,
		operate_correct_style_info,
	} = useMeetingTVWallStore(
		(state) => ({
			pollMembers: state.pollMembers,
			pollPlanName: state.pollPlanName,
			pollInterval: state.pollInterval,
			pollIntervalOptionsVal: state.pollIntervalOptionsVal,
			pollPlanOptions: state.pollPlanOptions,
			pollPlanValue: state.pollPlanValue,
			pollTimes: state.pollTimes,
			unlimited: state.unlimited,
			update: state.update,
			setBatchPollParams: state.setBatchPollParams,
			correct_style: state.correct_style,
			show_mt_name: state.show_mt_name,
			operate_correct_style_info: state.operate_correct_style_info,
		}),
		shallow
	)

	/**第二步:设置轮询预案下拉列表*/
	useEffect(() => {
		if (planList && planList.success) {
			let arr = planList.data ? planList.data.map((item) => ({ label: item.name, value: item.id })) : []
			arr.unshift({ label: t('不使用预案'), value: '0' })
			// setPlanOptions(arr)
			update({ pollPlanOptions: arr })
		}
	}, [planList])
	/**第三步:设置预案值*/
	useEffect(() => {
		// setPlanValue(pollPlanOptions.find((item) => item.label === pollData?.name)?.value ?? '0')
		update({ pollPlanValue: pollPlanOptions.find((item) => item.label === pollPlanName)?.value ?? '0' })
		setOpertePollCash()
	}, [pollPlanName, pollPlanOptions])
	/**设置批量轮询的缓存 */
	const setOpertePollCash = () => {
		const pollIntervalOptionsVal = useMeetingTVWallStore.getState().pollIntervalOptionsVal
		const pollInterval = useMeetingTVWallStore.getState().pollInterval
		const pollPlanValue = useMeetingTVWallStore.getState().pollPlanValue
		const pollPlanOptions = useMeetingTVWallStore.getState().pollPlanOptions
		const unlimited = useMeetingTVWallStore.getState().unlimited
		const pollTimes = useMeetingTVWallStore.getState().pollTimes
		const pollMembers = useMeetingTVWallStore.getState().pollMembers
		let source = {}
		let params = {
			id: '',
			mode: 1,
			name:
				pollPlanValue === '0' ? '' : pollPlanOptions.find((item) => item.value === pollPlanValue)?.label ?? '',
			keep_time:
				pollIntervalOptionsVal !== 0
					? pollIntervalOptionsVal
					: Number(pollInterval) === 0
					? -1
					: Number(pollInterval),
			num: unlimited ? 0 : Number(pollTimes) === 0 ? -1 : Number(pollTimes),
			members: pollMembers.map((item) => {
				return {
					account: item.account,
					account_type: item.account_type,
					name: item.name,
					parent_id: item.parent_id,
				}
			}),
		}
		source = Object.assign({}, operate_correct_style_info[correct_style], { batch_poll: params })
		operate_correct_style_info[correct_style] = source
		console.log('operate_correct_style_info****************批量轮询保存的缓存数据', operate_correct_style_info)
		update({ operate_correct_style_info: operate_correct_style_info })
	}
	const changePlan = async (id: string) => {
		// setPlanValue(id)
		update({ pollPlanValue: id })
		setOpertePollCash()
		if (id === '0') {
			initPollData(null)
			return
		}
		fetchGetPollPlanDetail(preKey, isTemplate, id).then((res) => {
			if (res.success) {
				initPollData(res)
			} else {
				initPollData(null)
			}
		})
	}

	useImperativeHandle(ref, () => ({
		testValue() {
			if (pollIntervalOptionsVal === 0) {
				if (pollInterval === '') {
					Alert(t('请设置轮询间隔'))
					return false
				} else if (Number(pollInterval) < 5 || Number(pollInterval) > 7200) {
					Alert(t('轮询间隔应为5~7200秒'))
					return false
				}
			}
			if (!unlimited) {
				if (pollTimes === '') {
					Alert(t('请设置轮询次数'))
					return false
				} else if (Number(pollTimes) < 1 || Number(pollTimes) > 9999) {
					Alert(t('轮询次数应为1~9999次'))
					return false
				}
			}
			if (pollMembers.length === 0) {
				Alert(t('批量轮询列表不能为空'))
				return false
			}
			return true
		},
		getValue() {
			return {
				id: '',
				mode: 1,
				name:
					pollPlanValue === '0'
						? ''
						: pollPlanOptions.find((item) => item.value === pollPlanValue)?.label ?? '',
				keep_time: pollIntervalOptionsVal !== 0 ? pollIntervalOptionsVal : Number(pollInterval),
				num: unlimited ? 0 : Number(pollTimes),
				members: pollMembers.map((item) => {
					return {
						account: item.account,
						account_type: item.account_type,
						name: item.name,
						parent_id: item.parent_id,
					}
				}),
			}
		},
	}))
	return (
		<StyledVmpPoll>
			<LabelWrap label={''} className="line_wrap_show_mt_name">
				<CheckBox
					checked={!!show_mt_name}
					onChange={(e, val) => {
						update({ show_mt_name: val ? 1 : 0 })
					}}
				>
					{t('显示终端名称')}
				</CheckBox>
			</LabelWrap>
			{!repeat && (
				<LabelWrap label={t('轮询预案')} className="line_wrap_vmp">
					<Select
						container={() => _container}
						options={pollPlanOptions}
						value={pollPlanValue}
						onChange={(e, v) => changePlan(v)}
					/>
				</LabelWrap>
			)}
			<LabelWrap label={t('轮询间隔')} className="line_wrap_vmp">
				<Select
					container={() => _container}
					width={100}
					options={pollIntervalOptions}
					value={pollIntervalOptionsVal}
					onChange={(e, v) => {
						update({ pollIntervalOptionsVal: v, pollInterval: '5' })
						/**缓存轮序间隔*/
						setOpertePollCash()
					}}
				/>
				{pollIntervalOptionsVal === 0 && (
					<div className="seconds">
						<div className="seconds_content">
							<InputNumber
								width={80}
								value={pollInterval}
								onChange={(e, v) => {
									update({ pollInterval: v })
									setOpertePollCash()
								}}
								maxLength={4}
							/>
							<span className="msg">{t('5~7200秒')}</span>
						</div>
						{pollInterval && (Number(pollInterval) < 5 || Number(pollInterval) > 7200) && (
							<div className="err_msg">{t('轮询间隔为5~7200秒')}</div>
						)}
					</div>
				)}
			</LabelWrap>
			<LabelWrap label={t('轮询次数')} className="line_wrap_vmp poll_num">
				<div className="poll_num_content">
					<InputNumber
						width={80}
						disabled={unlimited}
						value={pollTimes}
						onChange={(e, val) => {
							update({ pollTimes: val })
							setOpertePollCash()
						}}
						maxLength={4}
					/>
					<span className={`${unlimited ? 'disabled' : ''} msg`}>{t('1~9999次')}</span>
					<CheckBox
						className="unlimited"
						checked={unlimited}
						onChange={(e, val) => {
							update({ unlimited: val })
							setOpertePollCash()
						}}
					>
						{t('不限次数')}
					</CheckBox>
				</div>
				{!unlimited && pollTimes && (Number(pollTimes) < 1 || Number(pollTimes) > 9999) && (
					<div className="err_msg">{t('轮询次数为1~9999次')}</div>
				)}
			</LabelWrap>
			<LabelWrap label={t('轮询方列表')} className="line_wrap_vmp line_wrap_vmp_member ">
				<CreateMember
					title={t('已选')}
					width={540}
					height={320}
					list={pollMembers}
					setOuterList={(h, type) => {
						if (type === 'drop') {
							setTvwallPollList(h)
							setOpertePollCash()
						} else {
							update({ pollMembers: h })
							setOpertePollCash()
						}
					}}
					isHideOrder={false}
				></CreateMember>
			</LabelWrap>
		</StyledVmpPoll>
	)
})
export default TvwallPoll
